# 设置三方库安装路径
set(INSTALL_PREFIX ${CMAKE_BINARY_DIR}/third_party/z)

set(CACHE_DIR ${PROJECT_SOURCE_DIR}/testcache/zlib-1.2.13/zlib-1.2.13.tar.gz)
message(info, "local cache dir: ${CACHE_DIR}")
if (EXISTS ${CACHE_DIR}) 
    # 利用本地源码缓存
    include(ExternalProject)
    ExternalProject_Add(
        z
        URL ${CACHE_DIR}
        CMAKE_ARGS -DCMAKE_INSTALL_PREFIX=${INSTALL_PREFIX}
        DOWNLOAD_NO_PROGRESS FALSE
    )
    message(info, "use cache lib.")
else ()
    message(info, "not find cache lib, use online lib.")
    # 利用本地lib缓存
    # 查找头文件路径是否存在
    find_path(z_INCLUDE_DIR
        NAMES zlib.h
        PATHS ${INSTALL_PREFIX}/include/
        NO_DEFAULT_PATH
    )
    find_library(z_LIBRARY
        NAMES z
        PATHS ${INSTALL_PREFIX}/lib
        NO_DEFAULT_PATH
    )
    if (NOT ${z_INCLUDE_DIR} STREQUAL z_INCLUDE_DIR-NOTFOUND AND NOT ${z_LIBRARY} STREQUAL z_LIBRARY-NOTFOUND)
        set(z_FOUND TRUE)
        return ()
    endif ()

    # 采用外部下载
    if(NOT TARGET z)
        include(ExternalProject)
        ExternalProject_Add(
            z
            URL https://gitcode.com/cann-src-third-party/zlib/releases/download/v1.2.13/zlib-1.2.13.tar.gz
            CMAKE_ARGS -DCMAKE_INSTALL_PREFIX=${INSTALL_PREFIX}
            DOWNLOAD_NO_PROGRESS FALSE
        )
    endif ()
endif ()

find_path(z_INCLUDE_DIR
    NAMES zlib.h
    PATHS ${INSTALL_PREFIX}/include/
    NO_DEFAULT_PATH
)
find_library(z_LIBRARY
    NAMES z
    PATHS ${INSTALL_PREFIX}/lib
    NO_DEFAULT_PATH
)
if (NOT ${z_INCLUDE_DIR} STREQUAL z_INCLUDE_DIR-NOTFOUND AND NOT ${z_LIBRARY} STREQUAL z_LIBRARY-NOTFOUND)
    # 设置三方库安装成功标识符
    set(z_FOUND TRUE)
    # 导入编译结果至共享库
    add_library(z SHEAD IMPORTED)
    # 设置z的属性值, 供外部调用
    set_target_properties(z PROPERTIES
        INTERFACE_INCLUDE_DIRECTORIES ${z_INCLUDE_DIR}
        IMPORTED_LOCATION ${z_LIBRARY}
    )
endif ()

